from django.shortcuts import render
from .models import User
from .models import Product
from django.http import HttpResponse


# Create your views here.
# 添加一个用户
def add_user(request):
    u_name = request.GET.get('name')
    user = User.objects.create(u_name=u_name)
    return HttpResponse(f'添加成功，{user.u_name}')


# 添加一个商品
def add_product(request):
    p_name = request.GET.get('name')
    product = Product.objects.create(p_name=p_name)
    return HttpResponse(f'添加成功，{product.p_name}')


# 为用户和商品进行绑定
def binding(request):
    product = Product.objects.last()
    user = User.objects.last()
    p = product.p_user.add(user)
    return HttpResponse('成功！')


# 通过user来查找商品
def get_product(request):
    id = request.GET.get('id')
    user = User.objects.get(pk=id)   # 在进行多对多的查找时使用get进行查找
    product_list = user.product_set.all()
    return render(request, 'myapp/product.html', locals())


# 通过product来查找用户
def get_user(request):
    id = request.GET.get('id')
    product = Product.objects.get(pk=id)  # 在进行多对多的查找时使用get进行查找
    user_list = product.p_user.all()
    return render(request, 'myapp/user_list.html', locals())